package chabernac.android.wordbattle.db;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import chabernac.android.wordbattle.model.RandomLetterHelper;

public class InMemoryStringDB implements iStringDatabase {
  private final Map<String, Language> myLoadedWords = new HashMap<String, Language>();

  @Override
  public boolean isLanguageLoaded(String aLanguage) {
    return myLoadedWords.containsKey(aLanguage);
  }

  @Override
  public boolean isValidWord(String aLanguage, String aWord) {
    return myLoadedWords.get(aLanguage).getWords().contains(aWord.toUpperCase());
  }
  
  @Override
  public boolean isValidPrefix( String aLanguage, String aPrefix ) {
    List<String> theWords = myLoadedWords.get(aLanguage).getWords();
    for(String theWord : theWords){
      if(theWord.startsWith( aPrefix )) return true;
    }
    return false;
  }

  @Override
  public RandomLetterHelper getRandomLetterHelper(String aLanguage) {
    return myLoadedWords.get(aLanguage).getRandomLetterHelper();
  }

  @Override
  public void beginInsertingWords( String aLanguage ) {
    myLoadedWords.put( aLanguage, new Language( new RandomLetterHelper(), new ArrayList<String>() ) );
  }

  @Override
  public void endInsertingWords( String aLanguage ) {
    myLoadedWords.get(aLanguage).getRandomLetterHelper().calculateTotalLetterOccurance();
    
  }

  @Override
  public void insertWord( String aLanguage, String aWord ) throws IOException {
    myLoadedWords.get(aLanguage).addWord( aWord );
    
  }
  
  private class Language{
    private final RandomLetterHelper myRandomLetterHelper;
    private final List<String> myWords;

    public Language(RandomLetterHelper aRandomLetterHelper,
        List<String> aWords) {
      myRandomLetterHelper = aRandomLetterHelper;
      myWords = aWords;
    }

    public RandomLetterHelper getRandomLetterHelper() {
      return myRandomLetterHelper;
    }

    public List<String> getWords() {
      return myWords;
    }
    
    public void addWord(String aWord){
      myRandomLetterHelper.addWord( aWord );
      myWords.add(aWord);
    }
  }

  @Override
  public void insertingWordsCompleted( String aLanguage ) {
    // TODO Auto-generated method stub
    
  }

  @Override
  public void close() {
  }
}
